package com.hwj.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.io.PrintWriter;

/**
 * Spring security的配置类
 */
@Configuration
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //    @Autowired
//    private CustomAccessDeniedHandLer  customAccessDeniedHandLer;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //http.authorizeRequests()主要是对url 进行控制
        http.authorizeRequests()
                //允许匿名访问的资源
                .antMatchers("/userinfo/login","/userinfo/register","/webjars/**"
                        ,"/swagger-resources/**","/doc.html/**","/v2/**","/**").permitAll()
                .antMatchers("doc.html").anonymous()
                //必须有管理员角色才能访问role,permission,doctor
                .antMatchers("/permission/**","/user/**","/role/**").hasRole("superAdmin")
                //添加的是拥有特性角色才能访问的url链接  admin或者user,角色/patient/**
                .antMatchers("/userinfo/**").hasAnyRole("superAdmin")
                //任意的请求必须认证后才可以访问
                .anyRequest()
                .authenticated();
        //去除默认的登录页
        http.formLogin().disable();
        //默认增加了一个csrf校验,我们暂时将其禁用,否则前端无法登陆.
        http.csrf().disable();
        //自定义403响应结果
//        http.exceptionHandling().accessDeniedHandler(customAccessDeniedHandLer);
    }

    /*
     * 注入BCryptPasswordEncoder
     * 加密
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 继承关系
     * @return
     */
    @Bean
    RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
        hierarchy.setHierarchy("ROLE_superAdmin > ROLE_admin \n ROLE_admin > ROLE_powerUser \n ROLE_powerUser > ROLE_user");
        return hierarchy;
    }


    /*@Autowired
    @Qualifier("userinfoService")
    UserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }*/

}
